package com.uvnos4j.matilda.security.callback;


import com.uvnos4j.matilda.commons.dto.Result;
import com.uvnos4j.matilda.commons.utils.Const;
import com.uvnos4j.matilda.commons.utils.RequestUtil;
import com.uvnos4j.matilda.commons.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败回调
 * <p>
 * Description:认证失败回调
 * </p>
 *
 * @author Guo.wl
 * @version v1.0.0
 * @since 2020-08-16 23:44:54
 */
@Slf4j
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException, ServletException {
        String errorMsg = null;
        if (e instanceof UsernameNotFoundException) {
            errorMsg = "用户名或密码不正确";
        } else if (e instanceof DisabledException) {
            errorMsg = "用户已被禁用";
        } else if (e instanceof LockedException) {
            errorMsg = "账户锁定";
        } else if (e instanceof BadCredentialsException) {
            errorMsg = "用户名或密码不正确";
        } else if (e instanceof CredentialsExpiredException) {
            errorMsg = "密码过期";
        }

        log.error("[AuthenticationException]\r\n登录失败：{}，用户：{}。", e.getMessage(),
                httpServletRequest.getParameter("username"));

        if (RequestUtil.isAjax()) {
            ResponseUtil.writeJson(Result.fail(errorMsg));
        } else {
            // 转发到登录失败处理的 URL，请求方式 POST
            String loginFailedUrl = Const.AUTH_LOGIN_FAILED_URL + "=" + errorMsg;
            httpServletRequest.getRequestDispatcher(loginFailedUrl).forward(httpServletRequest, httpServletResponse);
        }
    }

}